package fastClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Header;
import protocol.IOMessage;
import protocol.MessageType;

public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter{

    public static String username;
    public static String password;
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception{

		IOMessage mes = buildLoginReq();
		System.out.println("1.client send login req-- > " + mes);
		ctx.writeAndFlush(mes);
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg){
		
		IOMessage message = (IOMessage) msg;
		System.out.println("client receive --> " + msg);
		
		if(message.getHeader() != null && message.getHeader().getType()
				                      == MessageType.LOGIN_RESP.value()){
			
		    JSONObject loginResult = JSON.parseObject(message.getBody());

		    //登录失败
			if(loginResult.get("login").equals("failure")){
				
				System.out.println("登录失败");
				ctx.close();
                
				/*
                 * 此处可插入APP代码				
                 */
				
			}else{//登录成功
				System.out.println("登录成功");
                ChatClient.ctx = ctx;
                
                /*
                 * 此处可插入APP代码				
                 */
                
			}
			ctx.fireChannelRead(msg);
		}else{
			ctx.fireChannelRead(msg);
		}
	} 
	
	private IOMessage buildLoginReq(){
		
		IOMessage message = new IOMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_REQ.value());
		message.setHeader(header);
		
		JSONObject loginJson = new JSONObject();
		loginJson.put("username", username);
		loginJson.put("password", password);
		
		message.setBody(loginJson.toJSONString());
		return message;
	}      
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
		 throws Exception {
		// TODO Auto-generated method stub
		ctx.fireExceptionCaught(cause);
	}
	
}